package com.cuicui.mall.service;

import com.cuicui.mall.dao.AppendixDataMapper;
import com.cuicui.mall.entity.AppendixData;
import com.cuicui.mall.vo.AppendixVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AppendixService {
    @Autowired
    private AppendixDataMapper AppendixDao;
    // 文件上传目标位置
    private static final String BASE_DIR = "D:\\app\\phpstudy_pro\\WWW\\static\\";
    // 文件预览地址
    private static final String BASE_URL = "http://localhost:81/";

    public AppendixVO upload (MultipartFile file){
        // 获取文件名成
        String fileName = file.getOriginalFilename();
        String fileType = file.getContentType();
        long fileSize = file.getSize();
        Date date = new Date();

        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String resultDate = formatDate.format(date);
        AppendixVO resultVo = new AppendixVO();
        try{
            // 新建一个文件路径
            resultVo.setName(fileName);
            resultVo.setType(fileType);
            File uploadFile = new File(BASE_DIR + resultDate + "\\file_"  + fileName);
            // 当父目录不存在时时、自动创建
            if(!uploadFile.getParentFile().exists()){
                uploadFile.getParentFile().mkdirs();
            }
            // 存储文件到磁盘
            file.transferTo(uploadFile);
            // 写入附件表
            if (uploadFile.exists() && uploadFile.length() > 0){
                AppendixData appendixData = new AppendixData();
                try {
                    appendixData.setSize(Math.toIntExact(fileSize));// 安全转换，超范围抛异常
                } catch (ArithmeticException e) {
                    System.out.println("数值超出int范围");
                }
                appendixData.setPath(BASE_URL + resultDate + "/file_"  + fileName);
                appendixData.setName(fileName);
                appendixData.setCreateTime(date);
                appendixData.setType(fileType);

                resultVo.setPath(BASE_URL + resultDate + "/file_"  + fileName);
                resultVo.setCreateTime(date);
                AppendixDao.insertSelective(appendixData);
            }
        }catch (IOException e){
            System.out.println(e.toString());
            e.printStackTrace();
        }

        return resultVo;
    }
}
